<?php
/*
 * @Author: your name
 * @Date: 2020-12-24 09:25:34
 * @LastEditTime: 2020-12-24 11:30:19
 * @LastEditors: Please set LastEditors
 * @Description: 资产组模块授权信息 这个文件要大改！！
 * @FilePath: /special/application/adminapiv3/model/ServerHostGroupModuleModel.php
 */

namespace app\adminapiv3\model;


use app\adminapiv3\service\platform_manage\ServerAuthService;
use think\Db;

class ServerHostGroupModuleModel extends BaseModel
{
    /**
     * 查询各个资产组在某个模块的授权主机总和
     * @param int $moduleId         模块id
     * @param int $exceptGroupId    排除的资产组id
     */
    public function getTotalAuthNum($moduleId,$exceptGroupId = 0){
        $where = [
            'module_id' => $moduleId, //只查询该模块的授权总数
        ];
        if($exceptGroupId){
            return $this->where($where)->where('group_id','neq',$exceptGroupId)->sum('number');
        }else{
            return $this->where($where)->sum('number');
        }
    }

    /**
     * 查询某个资产组的已授权模块数据
     * @param int       $groupId 资产组id
     * @param string    $field   查询字段
    */
    public function getGroupAuthInfo($groupId,$field = '*'){
        return $this->where('group_id',$groupId)->field($field)->select()->toArray();
    }

    /**
     * 查询某个资产组的已授权模块数据，包含模块信息
     * @param int       $groupId 资产组id
     * @param string    $field   查询字段
     */
    public function getGroupAuthDetail($groupId,$field = 'g.*,m.module_name'){
        return $this->alias('g')
            ->leftJoin('server_auth_module m','g.module_id=m.id')
            ->where('g.group_id',$groupId)->field($field)->select()->toArray();
    }

    /**
     * 查询某个资产组组的授权上限值信息
     * @param int       $groupId   资产组id
     * @param string    $moduleKey 模块标识
     * @param string    $field     查询字段
     */
    public function getGroupAuthLimit($groupId,$moduleKey,$field = 'g.number,g.etime'){
         return $this->alias('g')
            ->leftJoin('server_auth_module m','g.module_id=m.id')
            ->where([
                'g.group_id' => $groupId,
                'm.module_key' => $moduleKey
            ])->field($field)->findOrEmpty()->toArray();
    }

    /**
     * 根据资产组查询授权信息
     * @param int $groupId 资产组id
    */
    public function getAuthInfo($groupId){
        //1.查询授权基础信息
        $info = Db::name('server_auth')->field('unit_name, version_name')->find();
        //默认值
        $info['status'] = 1;
        //授权时间改为授权状态 1-正常 0-部分模块授权异常
        $modules = $this->getGroupAuthInfo($groupId,'etime');
        if(!$modules){
            $info['status'] = 0; //模块未授权
        }
        $modules = array_column($modules,'etime');
        //当前时间
        $authService = new ServerAuthService();
        $time = $authService->getSystemTime();
        foreach ($modules as $etime){
            if($time > $etime){
                $info['status'] = 0; //模块授权已过期
                break;
            }
        }
       return $info;
    }

}